# Replication archive for 
# Coppock, Alexander, Donald P. Green, and Ethan Porter. 2022. 
# Does Digital Advertising Affect Vote Choice? Evidence from a Randomized Field Experiment 
# Research & Politics. 

rm(list = ls())
# setwd() to replication archive

library(tidyverse)

# Helper functions --------------------------------------------------

bayes_updater <-
  function(estimate_1,
           std.error_1,
           estimate_2,
           std.error_2) {
    tibble(mu = weighted.mean(c(estimate_1, estimate_2), w = 1 / (c(
      std.error_1, std.error_2
    ) ^ 2)),
    sigma = sqrt(1 / ((1 / std.error_1 ^ 2) + (1 / std.error_2 ^ 2))))
  }

bayes_learning <-
  function(prior_mu, prior_sigma, experiments_df) {
    # initialize
    beliefs_df <-
      tibble(mu = prior_mu,
             sigma = prior_sigma,
             time = "Prior")
    # do all the updates
    for (i in 1:nrow(experiments_df)) {
      update_df <-
        bayes_updater(
          estimate_1 = beliefs_df$mu[i],
          std.error_1 = beliefs_df$sigma[i],
          estimate_2 = experiments_df$estimate[i],
          std.error_2 = experiments_df$std.error[i]
        )
      update_df$time <- paste0("Update ", i)
      beliefs_df <- bind_rows(beliefs_df, update_df)
    }
    return(beliefs_df)
  }

# Experimental Data -------------------------------------------------------

experiments_df <-
  tibble(
    estimate = c(0.016, 0.011, 0.009, -0.0004),
    std.error = c(0.014, 0.021, 0.006, 0.0085),
    study = factor(
      2:5,
      levels = 1:5,
      labels = c(
        "Prior",
        "Broockman and Green (2014)",
        "Turitto et al. (2014)",
        "Hager (2019)",
        "The present study"
      )
    ))


bayes_df <-
  bayes_learning(prior_mu = 0,
                 prior_sigma = 0.05,
                 experiments_df = experiments_df) %>%
  mutate(study = factor(
    1:5,
    levels = 1:5,
    labels = c(
      "Prior",
      "Broockman and Green (2014)",
      "Turitto et al. (2014)",
      "Hager (2019)",
      "The present study"
    )
  ))

gg_df <- 
  bayes_df %>%
  group_by(mu, sigma, time, study) %>%
  do(tibble(x = seq(-0.05, .05, 0.0001), 
            y = dnorm(x, mean = .$mu, sd = .$sigma)))

gg_df <-
  gg_df %>%
  left_join(experiments_df) %>%
  mutate(label =
           case_when(
             study == "Prior" ~ paste0(
               "Prior: ",
               "N(",
               sprintf("%.3f", mu),
               ",",
               sprintf("%.3f", sigma),
               ")"
             ),
             study != "Prior" ~ paste0(
               study, 
               "\n",
               "Estimate: ",
               sprintf("%.3f", estimate),
               " (SE: ",
               sprintf("%.3f", std.error),
               ")\n",
               "Posterior: ",
               "N(",
               sprintf("%.3f", mu),
               ", ",
               sprintf("%.3f", sigma),
               ")"
             )
           ))

# dput(unique(gg_df$label))

gg_df <-
  gg_df %>%
  mutate(label = factor(
    label, 
    levels = c(
      "Prior: N(0.000,0.050)",
      "Broockman and Green (2014)\nEstimate: 0.016 (SE: 0.014)\nPosterior: N(0.015, 0.013)",
      "Turitto et al. (2014)\nEstimate: 0.011 (SE: 0.021)\nPosterior: N(0.014, 0.011)",
      "Hager (2019)\nEstimate: 0.009 (SE: 0.006)\nPosterior: N(0.010, 0.005)",
      "The present study\nEstimate: -0.000 (SE: 0.009)\nPosterior: N(0.007, 0.004)"
    )
  ))



g <-
  ggplot(gg_df, aes(x = x, y = y)) +
  geom_line() + 
  geom_vline(xintercept = 0, linetype = "dashed", alpha = 0.5) +
  facet_grid(~label) +
  theme_bw() +
  geom_ribbon(
    data = . %>% filter(x > 0),
    aes(ymax = y, ymin = 0),
    fill = "lightgray",
    colour = NA,
    alpha = 0.5
  ) +
  scale_x_continuous(breaks = c(-0.03, 0, 0.03)) +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    legend.position = "none",
    strip.background = element_blank(),
    strip.text = element_text(size = 5),
    axis.text.x = element_text(size = 5),
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_blank()
  )

g

# ggsave("../output_for_overleaf/digital_bayes.pdf", g, width = 6.5, height = 1.9)

